﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;

namespace ElectronicCommerce.Framework.TcpHelper
{
    /// <summary>
    /// Default Message Serializer
    /// </summary>
    public class DefaultMessageSerializer : IMessageSerializer
    {
        private DataContractSerializer _formatter;

        private IEnumerable<Type> _knownType;

        private DefaultMessageSerializer()
        {
        }


        public DefaultMessageSerializer(IEnumerable<Type> knownType)
        {
            this._knownType = knownType;
        }

        #region IMessageSerializer Members

        public byte[] Serialize(MessageInfo message)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                _formatter = new DataContractSerializer(typeof(MessageInfo), _knownType);
                _formatter.WriteObject(stream, message);

                return stream.ToArray();
            }
        }

        public MessageInfo Deserialize(byte[] serializedMessage)
        {
            using (MemoryStream stream = new MemoryStream(serializedMessage) { Position = 0 })
            {
                _formatter = new DataContractSerializer(typeof(MessageInfo), _knownType);

                return (MessageInfo)_formatter.ReadObject(stream);
            }
        }

        #endregion
    }
}
